package com.loe.httptest

import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import com.chad.library.adapter.base.BaseViewHolder
import com.loe.json_ext.Json
import com.loe.json_ext.isEmpty
import com.loe.mvp.BaseActivity
import com.loe.mvp.ext_java.delay
import com.loe.mvp.ext_view.setDelayClickListener
import com.loe.mvp.list.QuickAdapter
import kotlinx.android.synthetic.main.activity_http_test.*
import kotlinx.android.synthetic.main.item_http_test.view.*

class HttpTestActivity : BaseActivity()
{
    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_http_test)

        SpHttpTest.isUpdate = true

        initView()
    }

    override fun onResume()
    {
        super.onResume()
        if (SpHttpTest.isUpdate)
        {
            loadData()
        }
    }

    override fun initView()
    {
        if(HttpTest.isTest)
        {
            titleView.imageLeftView.isVisible = false
        }else
        {
            titleView.textRightView.isVisible = false
        }

        recyclerView.adapter = adapter
        refreshLayout.adapter = adapter

        refreshLayout.setOnRefresh()
        {
            refreshLayout.loadOk()
            SpHttpTest.isUpdate = false
            refreshLayout.setData(DbHttpTest.getList())
        }

        titleView.setDelayRightListener()
        {
            openIntent(HttpSettingActivity::class).start()
        }

        buttonAdd.setDelayClickListener()
        {
            openIntent(HttpTestAddActivity::class).start()
        }
    }

    /**
     * 加载列表数据
     */
    override fun loadData()
    {
        refreshLayout.loadData()
    }

    /*************************************** 适配器 **************************************/

    private val adapter = object : QuickAdapter<HttpTestBean>(R.layout.item_http_test)
    {
        override fun View.convert(holder: BaseViewHolder, bean: HttpTestBean)
        {
            textName.text = bean.name
            textUrl.text = bean.url

            viewItem.setDelayClickListener()
            {
                openIntent(HttpTestAddActivity::class)
                    .putExtra("bean", bean)
                    .start()
            }

            buttonRequest.setDelayClickListener()
            {
                showLoading()
                bean.request()
                { s ->
                    cancelLoading()
                    bean.putResult(s)
                    toast(bean.result)
                    DbHttpTest.update(bean)
                }
            }

            buttonDelete.setOnClickListener()
            {
                DbHttpTest.delete(bean.id)
                remove(holder.layoutPosition)
            }
        }
    }
}